<template>
  <el-dropdown trigger="click" @command="handleLanguageChange">
    <div>
      <svg-icon icon-class="language" :size="size" />
    </div>
    <template #dropdown>
      <el-dropdown-menu>
        <el-dropdown-item
          v-for="item in supportedLanguages"
          :key="item.value"
          :disabled="appStore.language === item.value"
          :command="item.value"
        >
          {{ item.label }}
        </el-dropdown-item>
      </el-dropdown-menu>
    </template>
  </el-dropdown>
</template>

<script setup>
// src\components\common\LangSelect\index.vue
import {
  setLanguage,
  getCurrentLanguage,
  getSupportedLanguages,
  smartTranslate as $t,
} from '@/lang';
import { useAppStore } from '@/store/modules/app';
import { LanguageEnum } from '@/enums';

// 定义 props
const props = defineProps({
  size: {
    type: String,
    required: false,
  },
});

// 语言映射
const languageMap = LanguageEnum.ALL.reduce((acc, current) => {
  acc[current.value] = current.label;
  return acc;
}, {});

const appStore = useAppStore();
const supportedLanguages = ref([]);
const currentLanguage = ref('');

// 加载支持的语言列表
const loadSupportedLanguages = async () => {
  try {
    const languages = await getSupportedLanguages();
    supportedLanguages.value = languages.map((lang) => ({
      value: lang.code,
      label: languageMap[lang.code] || lang.code,
    }));
  } catch (error) {
    console.error('加载语言列表失败:', error);
    // 使用默认语言列表
    supportedLanguages.value = LanguageEnum.ALL;
  }
};

// 处理语言切换
const handleLanguageChange = async (langCode) => {
  if (langCode === currentLanguage.value) {
    return;
  }

  try {
    await setLanguage(langCode);
    // 更新当前组件的语言状态
    currentLanguage.value = langCode;
    ElMessage.success(
      $t('common.message.success.general', {
        action: $t('common.action.switch_language'),
      }),
    );
  } catch (error) {
    console.error('切换语言失败:', error);
    ElMessage.error(
      $t('common.message.failed.general', {
        action: $t('common.action.switch_language'),
      }),
    );
  }
};

// 初始化
onMounted(() => {
  currentLanguage.value = getCurrentLanguage();
  loadSupportedLanguages();
});
</script>

<style scoped>
/* 如果有特定的样式需求，可以在这里添加 */
</style>
